<template>
  <div class="autoOneContent my_loading" v-loading="loading">
    <!-- 信息配置参数 -->
    <div class="item_box">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" size="small">
        <el-row>
          <el-col class="item-title line" :sm="3" :md="3" :lg="3" :xl="3">信息配置参数</el-col>
          <el-col :sm="7" :md="7" :lg="7" :xl="7" class="item-box-l">
            <el-form-item label="设备序列码" prop="R_00030009">
              <el-input placeholder="读取中" v-model.trim="ruleForm.R_00030009" disabled></el-input>
            </el-form-item>
            <el-form-item label="设备编码" prop="R_00030008">
              <el-input placeholder="读取中" v-model.trim="ruleForm.R_00030008" disabled></el-input>
            </el-form-item>
            <el-form-item label="国标编码" prop="R_0003000b">
              <el-input placeholder="请输入" v-model.trim="ruleForm.R_0003000b" onkeyup="this.value = this.value.replace(/[^\d.]/g,'');" maxlength="20" :disabled="ruleFlag"></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="7" :md="7" :lg="7" :xl="7" class="item-box-l">
            <!-- v-model="massageVal" -->
            <el-form-item label="设备安装地址" prop="R_00030004">
              <!-- 此处需要根据行政规划区编码进行回显示 -->
              <!-- {{ruleForm.R_0003000a}} -->
              <el-input v-model.trim="ruleForm.R_00030004" v-show="!showcity" disabled></el-input>
              <!-- <el-cascader ref="cascaderAddr" v-show="showcity" v-model="ruleForm.R_0003000a" :options="massageOption" @change="handleChange" :disabled="ruleFlag"> </el-cascader> -->
              <el-cascader
                v-show="showcity"
                v-model.trim="massageVal"
                ref="cascaderList"
                @change="handleChange"
                clearable
                :props="{
                  lazy: true,
                  lazyLoad: lazyLoadAdd,
                }"
              ></el-cascader>
              <el-button type="primary" plain @click="selectCasc" :disabled="ruleFlag" style="margin-left: 5px">选择</el-button>
            </el-form-item>
            <el-form-item label="详细地址" prop="R_00030003">
              <el-input type="textarea" :rows="3" v-model.trim="ruleForm.R_00030003" placeholder="请输入" :disabled="ruleFlag"></el-input>
            </el-form-item>
            <el-form-item label="行政区划编码" prop="R_0003000a">
              <el-input placeholder="读取中" v-model.trim="ruleForm.R_0003000a" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="7" :md="7" :lg="7" :xl="7" class="item-box-r">
            <el-form-item label="所属运维机构" prop="R_00030005">
              <el-select v-model="ruleForm.R_00030005" :disabled="ruleFlag" @change="ywjgSelect" placeholder="请选择所属运维机构">
                <el-option v-for="item in jgOptions" :key="item.value" :label="item.label" :value="item.label"></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="运维单位名称" prop="R_00030006">
              <el-input placeholder="请输入运维单位名称" v-model="ruleForm.R_00030006" :disabled="ruleFlag"></el-input>
            </el-form-item>
            <el-form-item label="单位代码" prop="R_00030007">
              <el-input placeholder="运维单位代码" v-model="ruleForm.R_00030007" :disabled="ruleFlag"></el-input>
            </el-form-item>-->
            <el-button type="primary" class="btns_sbmit" :loading="messageLoad" @click="messageSubmit" :disabled="ruleFlag">提交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 系统配置参数 -->
    <div class="item_box">
      <el-form :model="ruleForm" :rules="sysRules" ref="systemForm" label-width="150px" size="small">
        <el-row>
          <el-col class="item-title line" :sm="3" :md="3" :lg="3" :xl="3">系统配置参数</el-col>
          <el-col :sm="7" :md="7" :lg="7" :xl="7" class="item-box-l">
            <el-form-item label="风扇启动温度(℃)" class="inputNumber" ref="numberElement">
              <!-- 内部风扇启动温度(℃) -->
              <!-- <el-input-number
                class="electricity"
                v-model="systemForm.R_00020003"
                controls-position="right"
                size="small"
                :disabled="systemFlag"
                :min="50"
              ></el-input-number>-->
              <el-input v-model.trim="systemForm.R_00020003" :disabled="systemFlag" placeholder="请输入" @input="handleInput($event, '00020003')"></el-input>
            </el-form-item>
            <!-- <el-form-item label="外部风扇启动温度(℃)" class="inputNumber">
              <el-input v-model="systemForm.R_00020004" :disabled="systemFlag" placeholder="请输入"></el-input>
            </el-form-item>-->
            <el-form-item label="风扇停止温度差值(℃)" class="inputNumber">
              <el-input v-model.trim="systemForm.R_00020024" :disabled="systemFlag" placeholder="请输入" @input="handleInput($event, '00020024')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="7" :md="7" :lg="7" :xl="7" class="item-box-l">
            <el-form-item label="DC标准电压(V)" class="inputNumber">
              <!-- <el-input-number
                class="electricity"
                v-model="systemForm.R_0002001e"
                controls-position="right"
                :min="0"
                size="small"
                disabled
              ></el-input-number>-->
              <el-input v-model.trim="systemForm.R_0002001e" placeholder="读取中" disabled></el-input>
            </el-form-item>
            <el-form-item label="DC标准电流(mA)" class="inputNumber">
              <!-- <el-input-number
                class="electricity"
                v-model="systemForm.R_0002001f"
                controls-position="right"
                :min="0"
                size="small"
                disabled
              ></el-input-number>-->
              <el-input v-model.trim="systemForm.R_0002001f" placeholder="读取中" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="7" :md="7" :lg="7" :xl="7" class="item-box-r">
            <el-form-item label="月冻结时间">
              <el-input v-model.trim="freezingTime.day" type="number" class="freezingTimeDay" placeholder="月冻结日" :disabled="systemFlag"></el-input>
              <el-time-picker v-model="freezingTime.time" placeholder="选择时间" value-format="HH:mm:ss" class="freezingTimeTime" :disabled="systemFlag"></el-time-picker>
            </el-form-item>
            <el-form-item label="年高位">
              <el-input v-model.trim="systemForm.R_0002001b" placeholder="读取中" disabled></el-input>
            </el-form-item>
            <el-button type="primary" class="btns_sbmit" :loading="systemLoad" :disabled="systemFlag" @click="systemSubmit">提交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 使能配置 -->
    <div class="item_box">
      <el-form :model="ruleForm" ref="infoParamsForm" label-width="150px" size="small">
        <el-row>
          <el-col class="item-title line" :sm="3" :md="3" :lg="3" :xl="3">使能配置</el-col>
          <el-col :sm="7" :md="7" :lg="7" :xl="7" class="item-box-l">
            <el-form-item label="外部时钟芯片使能" class="margin_bottom">
              <el-switch :value="enabledForm.R_0002001d" :active-icon-class="icon_0002001d" :active-value="1" :inactive-value="0" @change="enableBtn1" :disabled="d_0002001d"></el-switch>
            </el-form-item>
            <el-form-item label="计量模块使能" class="margin_bottom">
              <el-switch :value="enabledForm.R_00020022" :active-icon-class="icon_00020022" :active-value="1" :inactive-value="0" @change="enableBtn2" :disabled="d_00020022"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :sm="7" :md="7" :lg="7" :xl="7" class="item-box-l">
            <el-form-item label="掉电发送数据使能" class="margin_bottom">
              <el-switch :value="enabledForm.R_00020020" :active-icon-class="icon_00020020" :active-value="1" :inactive-value="0" @change="enableBtn3" :disabled="d_00020020"></el-switch>
            </el-form-item>
            <el-form-item label="上电发送数据使能" class="margin_bottom">
              <el-switch :value="enabledForm.R_00020021" :active-icon-class="icon_00020021" :active-value="1" :inactive-value="0" @change="enableBtn4" :disabled="d_00020021"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :sm="7" :md="7" :lg="7" :xl="7" class="item-box-r">
            <el-form-item label="GPS使能" class="margin_bottom">
              <el-switch :value="enabledForm.R_000f0006" :active-icon-class="icon_000f0006" :active-value="1" :inactive-value="0" @change="enableBtn5" :disabled="d_000f0006"></el-switch>
            </el-form-item>
            <el-form-item label="GPS辅助功能使能" class="margin_bottom">
              <el-switch :value="enabledForm.R_000f0008" :active-icon-class="icon_000f0008" :active-value="1" :inactive-value="0" @change="enableBtn6" :disabled="d_000f0008"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 地址选择弹出窗 -->
    <el-dialog :visible.sync="dialogWorkOrder" title="选择地址" class="workOrderClass" width="640px">
      <el-form>
        <el-form-item label="选择地址" style="margin-bottom: 200px">
          <el-cascader
            v-model.trim="massageVal"
            ref="cascaderAddr"
            @change="handleChange"
            clearable
            :props="{
              lazy: true,
              lazyLoad: lazyLoadAdd,
            }"
          ></el-cascader>
        </el-form-item>
        <el-form-item style="margin-bottom: 0; text-align: right">
          <el-button style="padding: 8px 15px" @click="faultClose">取消</el-button>
          <el-button style="padding: 8px 15px" type="primary" @click="submitForm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改提示窗 -->
    <el-dialog title="提示" :visible.sync="dialogStstusVisible" width="640px" @close="parentEvent">
      <statusPage :listStatus="listStatus" @child-event="closeDialog" />
    </el-dialog>
  </div>
</template>
<script>
import { ziC, pinT } from '@/utils/allUrl.js'
import { getUrl } from '@/utils/getUrl'
import { getUUID, isJSON, errorTips, overTimeTips, listTips, intervalTime, notChanges, send, sendPing, newSocket } from '@/utils/websocket'
import enumData from '@/utils/enum.json' // 枚举
import statusPage from '@/components/mainboard/listStatusTip'
import { linkageCity } from '@/utils/linkageCity.js'
export default {
  data() {
    return {
      socket: '',
      setIntervalWesocketPush: null,
      dialogStstusVisible: false, // 修改弹出窗
      listStatus: [], // 修改项数组
      value: '',
      // 级联选择器数据
      massageOption: [], // 乡镇街道
      jgOptions: [], // 所属机构
      showcity: false,
      ruleForm: {
        R_00030009: '', // 设备序列号
        R_00030008: '', // 设备编码
        R_0003000b: '', // 国标编码
        R_00030004: '', // 设备安装地址
        R_00030003: '', // 详细地址
        R_0003000a: '', // 行政区划编码
        R_00030005: '', // 所属运维机构
        // R_00030006: '', // 运维单位名称
        // R_00030007: '' // 单位代码
      },
      systemForm: {
        R_00020003: '', // 内部风扇启动温度
        // R_00020004: '', // 外部风扇启动温度
        R_00020024: '', // 风扇停止温度差值
        R_0002001e: '', // DC标准电压
        R_0002001f: '', // DC标准电流
        R_0002001a: '', // 月冻结时间
        R_0002001b: '', // 年高位
      },
      enabledForm: {
        R_0002001d: 0, // 外部时钟芯片使能
        R_00020022: 0, // 计量模块使能
        R_00020020: 0, // 掉电发送数据使能
        R_00020021: 0, // 上电发送数据使能
        R_000f0006: 0, // GPS使能
        R_000f0008: 0, // GPS辅助功能使能
      },
      ruleFormCopy: {}, // 信息配置copy
      systemFormCopy: {}, // 系统配置copy
      ruleFormSelected: [], // 信息配置input更改，存储input id
      systemFormSelected: [], // 系统配置
      ruleFlag: false,
      systemFlag: false,
      freezingTime: {
        // 月冻结时间
        day: '',
        time: '',
      },
      gprs: {}, // GPS使能的上报
      dialogVisible: false,
      dialogWorkOrder: false, // 弹窗
      massageVal: [], // 设备安装地址 存储
      cityVal: '', // 设备安装地址 转换ruleForm.R_00030004
      xqbm: '', // 辖区编码 转换ruleForm.R_0003000a
      xqbmArr: [],
      XQObj: {},
      messageLoad: false, // 信息配置 提价按钮状态
      systemLoad: false, // 系统配置 提交按钮状态
      selectedMess: [], // 信息配置保存更改之后的id
      icon_0002001d: '', // 外部时钟芯片使能 加载样式
      icon_00020022: '', // 计量模块使能 加载样式
      icon_00020020: '', // 掉电发送数据使能加载样式
      icon_00020021: '', // 上电发送数据使能加载样式
      icon_000f0006: '', // GPS使能加载样式
      icon_000f0008: '', // GPS辅助功能使能加载样式
      d_0002001d: false,
      d_00020022: false,
      d_00020020: false,
      d_00020021: false,
      d_000f0006: false,
      d_000f0008: false,
      username: '',
      timerNum: 0,
      loading: true,
      UUID: null,
      sysStatusFlag: false,
      ruleStatusFlag: false,
      sysList: [],
      ruleList: [],
      parentEventTimer: null,
      rules: {
        // R_0003000b: [{ required: true, message: '请输入国标编码', trigger: 'blur', pattern: '[^ \x22]+' }],
        R_00030003: [{ required: true, message: '请输入详细地址', trigger: 'blur', pattern: '[^ \x22]+' }],
        R_00030005: [{ required: true, message: '请输入所属运维机构', trigger: 'blur', pattern: '[^ \x22]+' }],
        R_00030006: [{ required: true, message: '请输入所属运维单位', trigger: 'blur', pattern: '[^ \x22]+' }],
        R_00030007: [{ required: true, message: '请输入单位代码', trigger: 'blur', pattern: '[^ \x22]+' }],
      },
      sysRules: {
        // R_00020003: [{ required: true, message: '121212', trigger: 'blur', pattern: /^\d+$|^\d+[.]?\d+$/ }]
        // R_00020003: [{ required: false, tigger: 'blur', validator: validateMoney }]
      },
      ruleAddress: true,
      ywjgSelected: {},
    }
  },
  components: { statusPage },
  created: function () {
    this.UUID = getUUID(32, 16)
    this.username = localStorage.getItem('userName') // 用户登录名
    this.getYwjg() // 运维机构
    // this.massageOption = JSON.parse(getUrl('district')) // 城镇街道
    // this.getStreetCodeEx('23090303')
    this.createSocket() // webSocket
    if (this.loading) {
      this.timer = setTimeout(() => {
        this.loading = false
        this.$message.error(overTimeTips)
      }, intervalTime)
    } else {
      clearTimeout(this.timer)
    }
  },
  mounted() {
    // this.getList()
  },
  watch: {
    'freezingTime.day': {
      immediate: false,
      handler(newVal, oldVal) {
        if (Number(newVal) > 31) {
          this.freezingTime.day = 31
        }
        this.freezingTime.day = this.freezingTime.day.replace(/^(0+)|[^\d]+/g, '')
      },
    },
    freezingTime: {
      // 月冻结时间检测
      deep: true,
      immediate: false,
      handler(newVal, oldVal) {
        let day = newVal.day
        if (newVal.day.toString().length < 2) {
          day = '0' + newVal.day
        }
        this.systemForm.R_0002001a = day + newVal.time.replace(/:/g, '')
        // console.log(day + newVal.time.replace(/:/g, ''))
      },
    },
    ruleForm: {
      // 信息配置参数
      deep: true,
      immediate: false,
      handler(newVal, oldVal) {
        if (Object.keys(this.ruleFormCopy).length === 0) {
          return
        }
        for (const i in newVal) {
          if (newVal[i] !== this.ruleFormCopy[i]) {
            if (this.ruleAddress && i === 'R_00030004') {
              continue
            }
            // console.log(this.ruleForm.R_00030004, '----', this.cityVal)
            this.ruleFormSelected.push(i)
          }
        }
      },
    },
    systemForm: {
      // 系统配置参数
      deep: true,
      immediate: false,
      handler(newVal, oldVal) {
        if (Object.keys(this.systemFormCopy).length === 0) {
          return
        }
        for (const i in newVal) {
          if (i === 'R_0002001e' || i === 'R_0002001f') {
            continue
          }
          if (newVal[i] !== this.systemFormCopy[i]) {
            this.systemFormSelected.push(i)
          }
        }
        // console.log(this.systemFormSelected)
      },
    },
  },
  methods: {
    // 根据用户管辖获取安装地址
    async lazyLoadAdd(node, resolve) {
      const user = JSON.parse(getUrl('userconter'))
      console.log(user)
      if (node.level === 0) {
        return resolve(await linkageCity(user.id, node.level + 1))
      } else if (node.level === 1) {
        return resolve(await linkageCity(user.id, node.level + 1, node.value))
      } else if (node.level === 2) {
        return resolve(await linkageCity(user.id, node.level + 1, node.value))
      } else if (node.level === 3) {
        return resolve(await linkageCity(user.id, node.level + 1, node.value, node.label))
      }
    },
    handleInput(value, id) {
      value = value.replace(/[^0-9.]/g, '')
      if (value.indexOf('.') > 0) {
        value = value.slice(0, value.indexOf('.') + 2)
      }
      this.systemForm[`R_${id}`] = value
    },
    // 建立websocket连接
    createSocket() {
      // // 在main.js或需要使用的地方引入并建立连接
      this.socket && this.socket.close()
      if (!this.socket) {
        console.log('建立websocket连接')
        this.socket = new WebSocket(newSocket(this.username, this.UUID))
        this.socket.onopen = this.open
        this.socket.onmessage = this.getMessage
        this.socket.onerror = this.onerror
        this.socket.onclose = this.onclose
      } else {
        console.log('websocket已连接')
      }
    },
    open() {
      this.getFirstId() // 第一包数据
      sendPing(this) // 发送心跳
    },
    // send第一次数据
    getFirstId() {
      // 发送id 获取数据
      const list = []
      this.getFor(this.ruleForm, list)
      this.getFor(this.systemForm, list)
      this.getFor(this.enabledForm, list)
      send(this, '01', list)
    },
    getMessage: function (msg) {
      switch (isJSON(msg.data)) {
        case false: // 主板实时数据
          break
        case true:
          // 接收到消息回复ok
          var SN = localStorage.getItem('SN')
          this.socket.send(`TILL${SN}OK`)
          if (typeof JSON.parse(msg.data) === 'object' && 'obj') {
            const res = JSON.parse(msg.data)
            var listS = []
            switch (Number(res.doing)) {
              case 1: // 读取数据
                // 状态码错误提示
                // console.log(res)
                if (res.host_status !== '0000') {
                  // errorTips(res.host_status)
                  errorTips(res.host_status, res.tips)
                  this.loading = false // 取消数据加载中样式
                  clearTimeout(this.timer)
                  return
                }
                if (res.list.length > 0) {
                  for (let i = 0; i < res.list.length; i++) {
                    var id = res.list[i].command_id.toLowerCase()
                    var content = res.list[i].value
                    if (id === '00020003' || id === '00020024') {
                      content = content.replace(/[^\d.]/g, '')
                    }
                    this.getInformation(this.enabledForm, content, id, 1)
                    this.getInformation(this.systemForm, content, id, 0)
                    this.getInformation(this.ruleForm, content, id, 0)
                    if (id === '0003000a') {
                      // 写入设备安装地址
                      this.getAdress(content, '00030004')
                    }
                  }
                }
                // 拷贝数据 信息配置参数 系统配置参数
                this.ruleFormCopy = JSON.parse(JSON.stringify(this.ruleForm))
                this.systemFormCopy = JSON.parse(JSON.stringify(this.systemForm))
                this.loading = false // 取消数据加载中样式
                break
              case 2: // 写入数据
                console.log('02主板和使能配置', res)
                res.list.forEach((item, index) => {
                  const id = item.command_id.toLowerCase()
                  // let val
                  if (item.status === '0001' || item.status === '2000') {
                    for (var k in this.enabledForm) {
                      // 使能开关判断
                      if (k.replace('R_', '') === id) {
                        if (Number(this.enabledForm[k]) === 0) {
                          this.enabledForm[k] = 1
                        } else {
                          this.enabledForm[k] = 0
                        }
                      }
                    }
                    //  修改成功提示push到list
                    listS.push({
                      name: enumData[`R_${item.command_id}`],
                      result: '修改成功',
                      status: 0,
                      id: item.command_id,
                    })
                    // if (id === '00030004') {
                    //   // 设备安装地址更改行政区划编码也是更改的 需要发送post请求
                    //   console.log('设备安装地址')
                    // }
                    // if (id === '00030004') {
                    //   // 详细地址
                    //   console.log('详细地址')
                    // }
                    // 006 清除要修改的数组
                    this.ruleFormSelected = []
                    this.systemFormSelected = []
                  } else {
                    // 修改失败
                    this.sysStatusFlag = false
                    listS.push({
                      name: enumData[`R_${item.command_id}`],
                      // result: listTips(item.status),
                      result: listTips(item.remarks),
                      status: 1,
                      id: item.command_id,
                    })
                  }
                })
                // 修改数据提示
                if (listS.length > 0) {
                  this.listStatusTips(listS)
                }
                // 设置为初始状态
                this.initDisable(false, 0)
                this.icon_0002001d = '' // 外部时钟芯片使能 加载样式
                this.icon_00020022 = '' // 计量模块使能 加载样式
                this.icon_00020020 = '' // 掉电发送数据使能加载样式
                this.icon_00020021 = '' // 上电发送数据使能加载样式
                this.icon_000f0006 = '' // GPS使能加载样式
                this.icon_000f0008 = '' // GPS辅助功能使能加载样式
                break
              default:
            }
            // 取消计时器
            clearTimeout(this.timer)
          }
          break
        default:
      }
    },
    // 修改提示
    async listStatusTips(list) {
      const XQ = ['SF', 'CS', 'QX', 'XZJD']
      const params = new URLSearchParams()
      let code = ''
      const paramsList = []
      list.forEach((item, index) => {
        // 0 成功  1 失败
        if (item.status === 0) {
          params.append('ID', localStorage.getItem('ID'))
          params.append('KQJY', 1)
          params.append('KQTBJY', 1)
          switch (item.id) {
            case '0003000a': // 行政区划编码
              params.append('XQBM', this.ruleForm.R_0003000a)
              paramsList.push(this.ruleForm.R_0003000a)
              break
            case '00030003': // 详细地址
              params.append('XXDZ', this.ruleForm.R_00030003)
              paramsList.push(this.ruleForm.R_00030003)
              break
            case '00030005': // 所属运维机构
              // params.append('YWDW', this.ruleForm.R_00030005)
              console.log(this.ywjgSelected)
              params.append('YWDW', this.ywjgSelected.value)
              paramsList.push(this.ruleForm.R_00030005)
              break
            case '0003000b': // 国标编码
              params.append('GBGM', this.ruleForm.R_0003000b)
              paramsList.push(this.ruleForm.R_0003000b)
              break
            case '00030004': // 设备安装地址
              // 保存省份 城市 区县 乡镇街道
              for (let i = 0; i < this.xqbmArr.length; i++) {
                params.append(XQ[i], this.xqbmArr[i])
                paramsList.push(this.xqbmArr[i])
              }
              params.append('SSQ_NO', this.xqbmArr[3])
              break
          }
        } else {
          code = ''
        }
      })
      console.log('--paramsList---', paramsList)
      if (paramsList.length > 0) {
        const { data: res } = await this.$http.post(`${ziC}zcgl/updateZiChan`, params)
        // console.log(res)
        if (res.code === '0000') {
          localStorage.setItem('XQBM', this.ruleForm.R_0003000a)
          code = 1
        } else {
          code = 0
        }
      }
      this.listStatus = {
        list: list,
        code: code,
      }
      console.log('-----', this.listStatus)
      this.dialogStstusVisible = true
    },
    closeDialog(data) {
      this.dialogStstusVisible = data
    },
    // 子组件触发父组件事件改编 dialogStstusVisible状态
    parentEvent(data) {
      if (this.parentEventTimer) {
        this.parentEventTimer = null
      }
      console.log(this.listStatus.list)
      const list = []
      // 修改成功同步数据
      this.listStatus.list.forEach((item, index) => {
        if (item.status === 0) {
          list.push({
            command_id: item.id,
            value: '',
          })
        }
      })
      console.log('---------', list)
      if (list.length > 0) {
        // 发送数据
        send(this, '01', list)
      }
      this.dialogStstusVisible = data
      if (list.length > 0) {
        this.loading = true
        this.parentEventTimer = setTimeout(() => {
          this.loading = false
        }, intervalTime)
      }
    },
    // 信息配置参数/系统配置参数/使能配置-赋值函数
    getInformation(arr, content, id, type) {
      for (const i in arr) {
        if (i === `R_${id}`) {
          if (i === 'R_0002001a') {
            this.freezingTime = {
              day: content.substring(0, 2),
              time: this.strInsert(content.substring(2, 8), 2, ':'),
            }
          }
          if (type === 1) {
            content = Number(content)
          }
          // 如果不是设备安装地址正常赋值
          if (i !== 'R_00030004') {
            arr[i] = content
          }
        }
      }
    },
    strInsert(str, length, text) {
      const reg = new RegExp('\\d{1,' + length + '}', 'g')
      const ma = str.match(reg)
      if (ma.join(text)) {
        return ma.join(text) // text 需要加的文本
      } else {
        return ''
      }
    },
    getFor(obj, list) {
      for (const k in obj) {
        list.push({
          command_id: k.replace('R_', ''),
          value: '',
        })
      }
    },
    // 信息配置参数-提交
    messageSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        this.showcity = false
        if (!valid) {
          return
        }
        const selectList = this.unique(this.ruleFormSelected)
        if (selectList.length < 1) {
          this.$message.warning(notChanges)
          return
        }
        // 不允许操作其他
        this.initDisable(true, 1)
        this.writeData(selectList, this.ruleForm, '0000')
        this.ruleStatusFlag = true
        setTimeout(() => {
          if (this.messageLoad) {
            this.initDisable(false, 0)
            this.$message.error('提交失败 请稍后重试')
          }
        }, intervalTime)
      })
    },
    // 系统配置参数-提交
    systemSubmit() {
      const selectList = this.unique(this.systemFormSelected)
      if (selectList.length < 1) {
        this.$message.warning(notChanges)
        return
      }
      if (this.freezingTime.day === '' || this.freezingTime.time === '') {
        this.$message.warning('请填写月冻结时间')
        return
      }
      // 不允许操作其他
      this.initDisable(true, 2)
      this.writeData(selectList, this.systemForm, '0001')
      this.sysStatusFlag = true
      // 没有返回数据执行下面操作
      setTimeout(() => {
        if (this.systemLoad) {
          this.initDisable(false, 2)
          this.sysStatusFlag = false
          this.$message.error('提交失败 请稍后重试')
        }
      }, intervalTime)
    },
    // 提交按钮调用事件
    writeData(arr, obj, btnNum) {
      if (this.socket.readyState === 1) {
        // arr 改变过input内容的id存储数组
        // obj 数据存储对象
        const list = []
        for (const i in arr) {
          for (const j in obj) {
            if (arr[i] === j) {
              var id = arr[i].replace('R_', '')
              var val = obj[j]
              if (arr[i] === 'R_00030004') {
                // 判断为设备安装地址的时候去掉/
                val = val.replace(/\//g, '')
              }
              list.push({
                command_id: id,
                value: val,
              })
            }
          }
        }
        // 发送数据
        send(this, '02', list)
      }
    },
    // 外部时钟
    enableBtn1() {
      const val = '0002001d'
      this.enable(val)
    },
    // 计量模块使能
    enableBtn2() {
      const val = '00020022'
      this.enable(val)
    },
    // 掉电发送数据使能
    enableBtn3() {
      const val = '00020020'
      this.enable(val)
    },
    // 上电发送数据使能
    enableBtn4() {
      const val = '00020021'
      this.enable(val)
    },
    // GPS使能
    enableBtn5() {
      const val = '000f0006'
      this.enable(val)
    },
    // GPS辅助功能使能
    enableBtn6() {
      const val = '000f0008'
      this.enable(val)
    },
    // 使能开关调用事件
    enable(val) {
      this['icon_' + val] = 'el-icon-loading'
      // this['d_' + val] = true
      this.initDisable(true, 0)
      let val2 = ''
      const list = []
      if (this.socket.readyState === 1) {
        if (this.enabledForm['R_' + val] === 0) {
          val2 = '1'
        } else {
          val2 = '0'
        }
        list.push({
          command_id: val,
          value: val2,
        })
        // 发送数据
        send(this, '02', list)
      }
      setTimeout(() => {
        if (this['icon_' + val] !== '') {
          this.$message.error('修改失败 稍后重试')
          this['icon_' + val] = ''
          // this['d_' + val] = false
          this.initDisable(false, 0)
        }
      }, 5000)
    },
    // 重置 加载样式
    initDisable(flag, type) {
      // type 0 全部  1信息配置参数  2系统配置参数  3使能配置
      switch (type) {
        case 1: // 信息配置参数
          this.messageLoad = flag
          break
        case 2: // 系统配置参数
          this.systemLoad = flag
          break
        // case 3: // 使能配置
        //   break
        default:
          this.messageLoad = flag
          this.systemLoad = flag
          break
      }
      this.systemFlag = flag
      this.ruleFlag = flag
      this.d_0002001d = flag
      this.d_00020022 = flag
      this.d_00020020 = flag
      this.d_00020021 = flag
      this.d_000f0006 = flag
      this.d_000f0008 = flag
    },
    // watch监听存储改变的值
    saveArr(newVal, objCopy, newArr) {
      for (const i in newVal) {
        if (newVal[i] !== objCopy[i]) {
          newArr.push(i)
        }
      }
    },
    // 返回值得切割
    getStr(str, firstStr, secondStr) {
      if (str === '' || str == null || str === undefined) {
        return ''
      }
      if (str.indexOf(firstStr) < 0) {
        return ''
      }
      var subFirstStr = str.substring(str.indexOf(firstStr) + firstStr.length, str.length)
      var subSecondStr = subFirstStr.replace(/\s*/g, '')
      if (secondStr !== '') {
        subSecondStr = subFirstStr.substring(0, subFirstStr.indexOf(secondStr)).replace(/\s*/g, '')
      }
      return subSecondStr
    },
    // 设备安装地址级联动选择器事件
    handleChange(e) {
      this.$nextTick(() => {
        const vals = this.$refs.cascaderList.presentText
        const xqbm = e[e.length - 1]
        this.ruleForm.R_0003000a = xqbm // 行政区划编码
        this.ruleForm.R_00030004 = vals // 设备安装地址
      })
      // if (e[e.length - 1].length < 7) {
      //   xqbm = e[e.length - 1] + '00'
      // }
      // this.xqbmArr = e
      // const arr = this.$refs.cascaderAddr.getCheckedNodes()[0].pathLabels
      // this.cityVal = arr.join('/') // 设备安装地址
      // this.xqbm = xqbm // 行政区划编码
    },
    // 设备安装地址选择按钮
    selectCasc() {
      this.$refs.cascaderList.toggleDropDownVisible() // 类似获取光标操作
      this.showcity = true
      // this.massageVal = [110000]
      // this.xqbm = '' // 辖区编码
      // this.cityVal = '' // 设备安装地址
      // this.massageVal = []
      // this.dialogWorkOrder = true
    },
    // 所属运维机构
    ywjgSelect(label) {
      this.jgOptions.forEach((item) => {
        if (item.label === label) {
          this.ywjgSelected = item
          console.log(this.ywjgSelected.value)
        }
      })
    },
    // 取消按钮-选择地址
    faultClose() {
      this.dialogWorkOrder = false
    },
    // 设备安装地址-确定
    submitForm() {
      if (this.cityVal === '') {
        return this.$message.warning('请选择地址')
      }
      this.ruleForm.R_0003000a = this.xqbm // 辖区编码
      this.ruleForm.R_00030004 = this.cityVal // 设备安装地址
      this.dialogWorkOrder = false
      this.ruleAddress = false
    },
    // 设备运维机构-请求
    async getYwjg() {
      const params = new URLSearchParams()
      params.append('jglx', 4) // 设备名称,IP条件
      const { data: res } = await this.$http.post('ptpz/zzjg/list', params)
      if (res.code !== '0000') {
        return
      }
      var arr = []
      res.data.list.forEach((item) => {
        const k = {
          value: item.id,
          label: item.jgmc,
          lxr: item.lxr,
          lxrdh: item.lxrdh,
        }
        arr.push(k)
      })
      this.jgOptions = arr
    },
    // 设备安装地址-请求
    async getAdress(adress, id) {
      const params = new URLSearchParams()
      params.append('streetCodeEx', adress)
      const { data: res } = await this.$http.post(`${pinT}district/find`, params)
      if (res.code !== '0000') {
        return
      }
      let address = ''
      address = res.data[0].provinceName + '/' + res.data[0].cityName + '/' + res.data[0].areaName + '/' + res.data[0].streetName
      const length = address.length
      if (address.charAt(length - 1) === '/') {
        address = address.substring(0, address.length - 1)
      }
      this.ruleForm[`R_${id}`] = address
      // this.ruleAddress = false
    },
    // 数组去重
    unique(arr) {
      var newArr = []
      for (var i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) === -1) {
          newArr.push(arr[i])
        }
      }
      return newArr
    },
    onerror(e) {
      this.socket.close()
      clearInterval(this.setIntervalWesocketPush)
      console.log('连接失败')
    },
    onclose(e) {
      clearInterval(this.setIntervalWesocketPush)
      console.log('websocket已断开')
      this.loading = false
      this.$message.error('websocket已断开')
    },
  },
  destroyed() {
    this.socket.send('CLOSE>-<' + this.username) // 关闭页面前发送
    // 销毁监听
    clearInterval(this.setIntervalWesocketPush)
    this.socket.onclose = this.socket.close()
    this.loading = false
    clearTimeout(this.timer)
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/scss/AutoOne.scss';
</style>
